package com.key.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.key.model.LoginHistory;
import com.key.model.User;
import com.key.tools.ConnectionPool;

@Controller
public class LoginController {
	@RequestMapping(value="/login")
	public ModelAndView login(User user,HttpServletRequest request){
		String url = "index";
		if(user==null){
			return new ModelAndView("index");
		}
		ConnectionPool cp = ConnectionPool.getInstance();
		Connection ct = cp.getConnection();
		try{
			PreparedStatement ps = ct.prepareStatement("select id,username,password,name,group_id from t_user where username = ? and password = md5("+user.getPassword()+")");
			ps.setString(1, user.getLoginName());
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				url = "main";
				user.setId(rs.getString("id"));
				user.setName(rs.getString("name"));
				user.setGroupId(rs.getString("group_id"));
				request.getSession().setAttribute("user", user);
				//写入日志
				PreparedStatement ps2 = ct.prepareStatement("insert into t_login_history(userid,login_time) values(?,?)");
				ps2.setString(1, user.getId());
				ps2.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
				ps2.executeUpdate();
				ps2.close();
			}
			rs.close();
			ps.close();
		}catch(Exception e){
			return new ModelAndView("index");
		}finally{
			try{
			ct.close();
			}catch(Exception e){
				return new ModelAndView("index");
			}
		}
		return new ModelAndView(url);
	}
	
	@RequestMapping(value="/logout")
	public ModelAndView logout(HttpServletRequest request){
		request.getSession().setAttribute("user", null);
		return new ModelAndView("index");
	}
}
